import axios from 'axios'

const api = axios.create()

// 添加请求拦截器
api.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 添加响应拦截器
api.interceptors.response.use(
  response => response,
  error => {
    if (error.response?.status === 401) {
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      window.location.href = '/login'
    }
    return Promise.reject(error)
  }
)

export const login = async (loginData) => {
  try {
    const response = await api.post('/api/auth/login', loginData)
    return response
  } catch (error) {
    if (error.response) {
      // 从后端获取更详细的错误信息
      const errorMessage = error.response.data.message || '登录失败'
      throw new Error(errorMessage)
    } else if (error.request) {
      throw new Error('服务器无响应，请检查网络连接')
    } else {
      throw new Error('请求配置错误')
    }
  }
}

export const register = async (registerData) => {
  try {
    const response = await api.post('/api/auth/register', registerData)
    return response
  } catch (error) {
    if (error.response) {
      // 从后端获取更详细的错误信息
      const errorMessage = error.response.data.message || '注册失败'
      throw new Error(errorMessage)
    } else if (error.request) {
      throw new Error('服务器无响应，请检查网络连接')
    } else {
      throw new Error('请求配置错误')
    }
  }
}

export const logout = () => {
  return api.post('/api/auth/logout')
}

export const getCaptcha = (type = 'MATH') => {
  return api.get(`/api/auth/captcha?type=${type}`)
}

export default api 